package cn.edu.sjtu.se.dslab.dao.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Repository;

import cn.edu.sjtu.se.dslab.component.data.EntityDiagram;
import cn.edu.sjtu.se.dslab.dao.IBaseDao;
import cn.edu.sjtu.se.dslab.dao.IDiagramDao;
import cn.edu.sjtu.se.dslab.util.Const;
import cn.edu.sjtu.se.dslab.util.MD5;

@Repository("diagramDao")
public class DiagramDaoImpl implements IDiagramDao {
	private static final String URI = "uri";
	@Resource(name = "baseDao")
	private IBaseDao<EntityDiagram> baseDao;

	@Override
	public void save(EntityDiagram diagram) {
		// TODO Auto-generated method stub
		String temp = diagram.getFilepath() +
				+  System.currentTimeMillis();
		MD5 md5 = new MD5();
		String uri = md5.getMD5ofStr(temp).substring(0, 8);
		while (!checkUri(Const.URI_DIAGRAM + ":" +uri)) {
			temp = diagram.getFilepath() +
					+  System.currentTimeMillis();
			uri = md5.getMD5ofStr(temp).substring(0, 8);
		}
		diagram.setUri(Const.URI_DIAGRAM + ":" + uri);
		baseDao.save(diagram);
	}

	@Override
	public void update(EntityDiagram diagram) {
		// TODO Auto-generated method stub
		baseDao.update(diagram);
	}

	@Override
	public EntityDiagram queryById(long id) {
		// TODO Auto-generated method stub
		return baseDao.queryById(EntityDiagram.class, id);
	}

	@Override
	public EntityDiagram queryByUri(String uri) {
		// TODO Auto-generated method stub
		StringBuffer hql = new StringBuffer();
		// 拼接sql语句
		hql.append("from EntityDiagram where ");
		hql.append(URI + "=");
		hql.append("'" + uri + "'");
		return baseDao.queryObject(hql.toString());
	}

	@Override
	public boolean checkUri(String uri) {
		// TODO Auto-generated method stub
		EntityDiagram diagram = queryByUri(uri);
		if (diagram != null) {
			return false;
		} else {
			return true;
		}
	}

}
